package com.boc.langxiang.ui.fragment.me;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.ImageContract;
import com.boc.langxiang.contract.me.MeContract;
import com.boc.langxiang.entity.events.LoginSuccessEvent;
import com.boc.langxiang.entity.events.NickNameChangeEvent;
import com.boc.langxiang.entity.response.UserInfo;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.presenter.ImagePresenter;
import com.boc.langxiang.presenter.me.MePresenter;
import com.boc.langxiang.ui.activity.me.AboutFlowOutActivity;
import com.boc.langxiang.ui.activity.me.AccountSetActivity;
import com.boc.langxiang.ui.activity.me.ConcernsActivity;
import com.boc.langxiang.ui.activity.me.LeaveToFlowOutActivity;
import com.boc.langxiang.ui.activity.me.MyCollectionsActivity;
import com.boc.langxiang.ui.activity.me.MyExerciseActivity;
import com.boc.langxiang.ui.activity.me.OrdersActivity;
import com.boc.langxiang.ui.activity.shop.ShoppingCarActivity;
import com.boc.langxiang.ui.dialog.ContactCustomerDialogFragment;
import com.boc.langxiang.ui.dialog.WeiXinCustomerDialogFragment;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.ui.view.MeViewItem;
import com.boc.langxiang.ui.view.SongTextView;
import com.boc.langxiang.ui.view.roundedimageview.RoundedImageView;
import com.boc.langxiang.util.KeyBoardUtil;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.GlideImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人中心
 */

public class MeFragment extends BaseFragment implements MeContract.View, ImageContract.View {

    @BindView(R.id.tv_me_title)
    TextView tvMeTitle;
    @BindView(R.id.iv_me_set)
    ImageView ivMeSet;


    @BindView(R.id.mvi_me_exercise)
    MeViewItem mviMeExercise;
    @BindView(R.id.mvi_me_collection)
    MeViewItem mviMeCollection;
    @BindView(R.id.mvi_me_service)
    MeViewItem mviMeService;
    @BindView(R.id.mvi_me_about)
    MeViewItem mviMeAbout;
    @BindView(R.id.civ_me_head)
    RoundedImageView civMeHead;
    @BindView(R.id.linlayout_me_head)
    LinearLayout linlayoutMeHead;
    @BindView(R.id.linlayout_me_head1)
    LinearLayout linlayoutMeHead1;
    @BindView(R.id.stv_me_name)
    SongTextView stvMeName;
    @BindView(R.id.stv_me_works)
    SongTextView stvMeWorks;
    @BindView(R.id.stv_me_professtion)
    SongTextView stvMeProfesstion;
    @BindView(R.id.stv_me_heats)
    SongTextView stvMeHeats;
    @BindView(R.id.stv_me_name1)
    SongTextView stvMeName1;
    @BindView(R.id.mvi_me_outflow)
    MeViewItem mviMeOutflow;

    private ImagePicker imagePicker;
    private ImageItem mImageItem;
    private MeContract.Presenter mPresenter;
    private String mPhotoId;
    private ImageContract.Presenter mImagePresenter;
    private boolean mIsOnActivityResult;
    private boolean mIsHasResume;
    private ContactCustomerDialogFragment mCustomDialogFragment;
    private WeiXinCustomerDialogFragment mWeiXinDialogFragment;

    public static MeFragment newInstance() {
        MeFragment fragment = new MeFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        Log.d("MeFragment", "getActivity().getWindow().getAttributes().flags:" + getActivity().getWindow().getAttributes().flags);
     /*   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(getActivity());
        tintManager.setTintAlpha(0f);
        tintManager.setStatusBarTintEnabled(true);*/

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        talkVisibile();

        mPresenter = new MePresenter(this);
        mImagePresenter = new ImagePresenter(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        KeyBoardUtil.closeKeybord(getActivity());
    }

    @OnClick({R.id.stv_me_orders, R.id.stv_me_shoppingcart, R.id.stv_me_concern, R.id.mvi_me_exercise,
            R.id.mvi_me_collection, R.id.iv_me_set, R.id.mvi_me_about, R.id.mvi_me_service, R.id.mvi_me_outflow,
            R.id.civ_me_head})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.stv_me_orders:
                startActivity(new Intent(getActivity(), OrdersActivity.class));
                // startActivity(new Intent(getActivity(), TestActivity.class));
                break;
            case R.id.stv_me_shoppingcart:
                startActivity(new Intent(getActivity(), ShoppingCarActivity.class));
                break;
            case R.id.stv_me_concern:
                startActivity(new Intent(getActivity(), ConcernsActivity.class));
                break;
            case R.id.mvi_me_exercise:
                startActivity(new Intent(getActivity(), MyExerciseActivity.class));
                break;
            case R.id.mvi_me_collection:
                startActivity(new Intent(getActivity(), MyCollectionsActivity.class));
                break;
            case R.id.iv_me_set:
                startActivity(new Intent(getActivity(), AccountSetActivity.class));
                break;
            case R.id.mvi_me_about:
                startActivity(new Intent(getActivity(), AboutFlowOutActivity.class));
                break;
            case R.id.mvi_me_service:
                mCustomDialogFragment = new ContactCustomerDialogFragment();
                mCustomDialogFragment.setBackCancelAble(true);
                mCustomDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar);
                mCustomDialogFragment.show(getChildFragmentManager(), "");
                mCustomDialogFragment.setCustomerListener(new ContactCustomerDialogFragment.CustomerListener() {
                    @Override
                    public void phoneClick() {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + "18957127620"));
                        MeFragment.this.startActivity(intent);
                    }

                    @Override
                    public void weiXinClick() {
                        mCustomDialogFragment.dismiss();
                        // TODO: 2016/7/25 公众号没具体给 测试
                        mWeiXinDialogFragment = new WeiXinCustomerDialogFragment();
                        mWeiXinDialogFragment.setBackCancelAble(true);
                        mWeiXinDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar);
                        mWeiXinDialogFragment.show(getChildFragmentManager(), "");
                        mWeiXinDialogFragment.setCustomerListener(new WeiXinCustomerDialogFragment.WeiXinCommonListener() {
                            @Override
                            public void OutSideTouch() {
                                mWeiXinDialogFragment.dismiss();
                            }
                        });
                    }

                    @Override
                    public void cancelClick() {
                        mCustomDialogFragment.dismiss();
                    }

                    @Override
                    public void emptyClick() {
                        mCustomDialogFragment.dismiss();
                    }
                });
                break;
            case R.id.mvi_me_outflow:
                startActivity(new Intent(getActivity(), LeaveToFlowOutActivity.class));
                break;
            case R.id.civ_me_head:
                imagePick();
                break;
        }
    }

    private void imagePick() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(GlideImageLoader.getInstance());
        imagePicker.setShowCamera(true);
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        imagePicker.setOutPutX(200);
        imagePicker.setOutPutY(200);
        imagePicker.setFocusWidth(600);
        imagePicker.setFocusHeight(600);
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> tempImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                mImageItem = tempImages.get(0);
                mIsOnActivityResult = true;
            } else {
                T.showShort(mContext, "没有数据");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsOnActivityResult) {
            mImagePresenter.uploadFile(mImageItem.path);
            mIsOnActivityResult = false;
        }

        if (!mIsHasResume) {
            setMeMessage();
            mIsHasResume = true;
        }
    }

    private void modifyHead() {
        mPresenter.modifyHead(mPhotoId);
    }

    @Override
    public void showLoading() {
        showProgressDialog("上传头像...");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, "头像修改失败!");
    }

    @Override
    public void modifyHeadSuccess() {
        PicassoImageLoader.getInstance().displayFileImage(mContext, mImageItem.path, civMeHead);
        T.showShort(mContext, "头像修改成功!");
    }

    @Override
    public void uploadFileFailed() {
        T.showShort(mContext, "头像修改失败!");
    }

    @Override
    public void uploadFileSuccess(String content) {
        mPhotoId = content;
        modifyHead();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            //setMeMessage();
        }
        super.onHiddenChanged(hidden);
    }

    private void setMeMessage() {
        UserInfo userInfo = UserInfoManager.getInstance().getUserInfo();
        if (userInfo != null) {
            int status = userInfo.getStatus();
            if (status == 2 || status == 3) {
                linlayoutMeHead.setVisibility(View.VISIBLE);
                linlayoutMeHead1.setVisibility(View.GONE);
//                mviMeOutflow.setVisibility(View.VISIBLE);
                stvMeName.setText(StringUtil.isEmpty(userInfo.getNickname()) ? "" : userInfo.getNickname());
                stvMeProfesstion.setText(StringUtil.isEmpty(userInfo.getZhiwu()) ? "暂无职务" : userInfo.getZhiwu());
                stvMeWorks.setText(StringUtil.isEmpty(userInfo.getOwn_product_count()) ? "0" : userInfo.getOwn_product_count());
                stvMeHeats.setText(StringUtil.isEmpty(userInfo.getOwn_click_count()) ? "0" : userInfo.getOwn_click_count());

            } else {
                linlayoutMeHead.setVisibility(View.GONE);
                linlayoutMeHead1.setVisibility(View.VISIBLE);
//                mviMeOutflow.setVisibility(View.GONE);
                stvMeName1.setText(StringUtil.isEmpty(userInfo.getNickname()) ? "" : userInfo.getNickname());
            }
            PicassoImageLoader.getInstance().displayUrlImage(mContext, userInfo.getPhotourl(), civMeHead);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent e) {
        setMeMessage();

        talkVisibile();
    }

    private void talkVisibile() {
        mviMeOutflow.setVisibility(View.GONE);
        UserInfo userInfo = UserInfoManager.getInstance().getUserInfo();
        if (userInfo != null) {
            int status = userInfo.getStatus();
            if (status == 2 || status == 3) {
                mviMeOutflow.setVisibility(View.VISIBLE);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setNickName(NickNameChangeEvent e) {
        setMeMessage();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}